package com.yuanda.erp9.syn.service.erp9.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yuanda.erp9.syn.contant.RateCalculateConstants;
import com.yuanda.erp9.syn.entity.CmsBrandsTempEntity;
import com.yuanda.erp9.syn.entity.CmsGoodsEntity;
import com.yuanda.erp9.syn.entity.CmsGoodsInformationEntity;
import com.yuanda.erp9.syn.entity.CmsPricesEntity;
import com.yuanda.erp9.syn.enums.CachePrefixEnum;
import com.yuanda.erp9.syn.enums.DeliveryAreaEnum;
import com.yuanda.erp9.syn.enums.SourceEnum;
import com.yuanda.erp9.syn.execule.thread.Master;
import com.yuanda.erp9.syn.helper.CoreStaffExcelHelper;
import com.yuanda.erp9.syn.helper.RetryOperateLogHelper;
import com.yuanda.erp9.syn.poi.CoreStaffStockExcelData;
import com.yuanda.erp9.syn.pojo.CmsGoodsPojo;
import com.yuanda.erp9.syn.service.erp9.CmsTopicUpdateSumLogService;
import com.yuanda.erp9.syn.service.erp9.CoreStaffStockExcelService;
import com.yuanda.erp9.syn.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;

/**
 * @ClassName CoreStaffStockExcelServiceImpl
 * @Description CoreStaffStockExcel实现类
 * @Date 2022/11/24
 * @Author myq
 */
@Service
@Slf4j
public class CoreStaffStockExcelServiceImpl implements CoreStaffStockExcelService {


    @Autowired
    private RetryOperateLogHelper retryOperateLogHelper;

    @Autowired
    private CmsTopicUpdateSumLogService cmsTopicUpdateSumLogService;


    /**
     * 供应商参数
     */
    private final String US_CODE = "US000000050";
    private final String SUPPLIER = "Corestaff";

    public String domesticDate = " 5-7个工作日";
    public String hongkongDate = " 3-5个工作日";


    /**
     * @Description: 解析excel并推送至队列
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2022/11/2417:22
     */
    @Override
    public void parse(String filePath, Long pk) {
        AtomicInteger sum = new AtomicInteger(0);
        Integer supplierId = CacheUtil.init(CachePrefixEnum.SUPPLIERS.getKey()).get(SUPPLIER);
        // 主任务类
        Master<CmsGoodsPojo> master = new Master<>(supplierId, null, SourceEnum.EMAIL.getCode());
        try {
            // 多个sheet
            for (String sheetName : CoreStaffExcelHelper.sheets) {
                EasyExcelUtils.readExcelBySheet(filePath, CoreStaffStockExcelData.class, new Consumer<CoreStaffStockExcelData>() {
                    @Override
                    public void accept(CoreStaffStockExcelData coreStaffStockExcelData) {
                        try {
                            sum.incrementAndGet();
                            // 包装类
                            CmsGoodsPojo cmsGoodsPojo = new CmsGoodsPojo();
                            //商品类
                            CmsGoodsEntity cmsGoodsEntity = new CmsGoodsEntity();
                            cmsGoodsEntity.setAdminid(0);
                            cmsGoodsEntity.setTenantsid(0);
                            // 处理后批次号
                            String dc = EasyExcelUtils.parseBatchNo(coreStaffStockExcelData.getDc());
                            cmsGoodsEntity.setClassifyid(0);
                            cmsGoodsEntity.setImg("");
                            cmsGoodsEntity.setType(0);
                            cmsGoodsEntity.setStatus(1);
                            cmsGoodsEntity.setStatusMsg("");
                            cmsGoodsEntity.setDataType(1);
                            cmsGoodsEntity.setModel(coreStaffStockExcelData.getPn());
                            String mfg = StringUtils.isEmpty(coreStaffStockExcelData.getMfg()) ? "unknown_brand" : coreStaffStockExcelData.getMfg();
                            // 型号名称为空
                            CmsBrandsTempEntity cmsBrandsTempEntity = new CmsBrandsTempEntity();
                            cmsBrandsTempEntity.setTag(0);
                            cmsBrandsTempEntity.setName(mfg);
                            Integer brandId = CacheUtil.init(CachePrefixEnum.BRAND.getKey()).insertAndGet(cmsBrandsTempEntity);
                            cmsGoodsEntity.setBrand(brandId);
                            cmsGoodsEntity.setBrandName(coreStaffStockExcelData.getMfg());
                            cmsGoodsEntity.setSupplier(supplierId);
                            cmsGoodsEntity.setSplName(SUPPLIER);
                            String incodes = EasyExcelUtils.getIncodes(coreStaffStockExcelData.getId(), US_CODE, supplierId);
                            cmsGoodsEntity.setIncodes(incodes);
                            cmsGoodsEntity.setGoodid(incodes);
                            cmsGoodsEntity.setIsSampleApply(0);
                            cmsGoodsEntity.setBatch(dc);
                            cmsGoodsEntity.setOriginalPrice(new BigDecimal("0.00"));
                            cmsGoodsEntity.setPurchasePrice(new BigDecimal("0.00"));
                            cmsGoodsEntity.setRepertory(Integer.valueOf(coreStaffStockExcelData.getQty()));
                            cmsGoodsEntity.setRepertoryArea("海外");
                            cmsGoodsEntity.setPublish(1);
                            cmsGoodsEntity.setDescribe("");
                            cmsGoodsEntity.setFiles("");
                            cmsGoodsEntity.setPayType(0);
                            cmsGoodsEntity.setIncremental(1L);
                            cmsGoodsEntity.setMpq(StringUtils.isEmpty(coreStaffStockExcelData.getMoq()) ? 1L : Long.parseLong(coreStaffStockExcelData.getMoq()));
                            cmsGoodsEntity.setDomesticDate(domesticDate);
                            cmsGoodsEntity.setHongkongDate(hongkongDate);
                            cmsGoodsEntity.setDeliveryArea(DeliveryAreaEnum.OTHER.getCode());
                            cmsGoodsEntity.setHisp("");
                            cmsGoodsEntity.setSales(0);
                            cmsGoodsEntity.setClick(0);
                            cmsGoodsEntity.setVisitor(0);
                            cmsGoodsEntity.setCreatedAt(DateUtils.now());
                            cmsGoodsEntity.setUpdatedAt(DateUtils.now());
                            cmsGoodsEntity.setSource(SourceEnum.EMAIL.getCode());
                            cmsGoodsEntity.setActivityId(0);
                            //费率
                            JSONObject data = RateCalculateUtil.getRate(cmsGoodsEntity.getBrandName(), cmsGoodsEntity.getModel());
                            // 费率信息
                            JSONObject rateJsonObject = (JSONObject) data.get(RateCalculateConstants.RATE);
                            cmsGoodsEntity.setRates(rateJsonObject);
                            //关税
                            BigDecimal tariffRate = rateJsonObject.getBigDecimal(RateCalculateConstants.TARIFFRATE_FIELD);
                            //商检税
                            BigDecimal cIQprice = rateJsonObject.getBigDecimal(RateCalculateConstants.CIQPRICE_FIELD);
                            //税费计算和存储
                            if (tariffRate != null) {
                                cmsGoodsEntity.setTariffsRate(tariffRate.doubleValue());
                            }
                            if (cIQprice != null) {
                                cmsGoodsEntity.setInspectionChargesFee(cIQprice.doubleValue());
                            }
                            cmsGoodsEntity.setEmbargo(data.get(RateCalculateConstants.EMBARGO_FIELD) == null ? 0 : data.getInteger(RateCalculateConstants.EMBARGO_FIELD));
                            cmsGoodsEntity.setCcc(data.get(RateCalculateConstants.CCC_FIELD) == null ? 0 : data.getInteger(RateCalculateConstants.CCC_FIELD));
                            cmsGoodsEntity.setEccnNo(data.getString(RateCalculateConstants.ECCN_FIELD));

                            // 参数
                            Map<String, String> paramMap = new LinkedHashMap<>();
                            paramMap.put("STOCK TYPE", coreStaffStockExcelData.getStockType());
                            paramMap.put("COO", coreStaffStockExcelData.getCoo());
                            cmsGoodsEntity.setParams(JSON.toJSONString(paramMap));
                            cmsGoodsEntity.setMinimumOrder(1L);
                            // 阶梯价格
                            List<Map<String, String>> ladderPrice = CoreStaffExcelHelper.getLadderPrice(sheetName, coreStaffStockExcelData.getPrice1(), coreStaffStockExcelData.getPrice2(), coreStaffStockExcelData.getPrice3(),
                                    coreStaffStockExcelData.getPrice4(), coreStaffStockExcelData.getPrice5(), coreStaffStockExcelData.getPrice6(), coreStaffStockExcelData.getPrice7(),
                                    coreStaffStockExcelData.getPrice8());
                            if (!CollectionUtils.isEmpty(ladderPrice)) {
                                cmsGoodsEntity.setMinimumOrder(Math.max(Integer.parseInt(ladderPrice.get(0).get("min")), cmsGoodsEntity.getMinimumOrder()));
//                                cmsGoodsEntity.setUnitPrice(Double.parseDouble(MathUtil.divide(ladderPrice.get(0).get("price"), cmsGoodsEntity.getMinimumOrder())));
                            } else {
                                cmsGoodsEntity.setUnitPrice(0.0000);
                            }
                            cmsGoodsEntity.setPrices(JSON.toJSONString(ladderPrice));
                            cmsGoodsEntity.setContent(null);
                            cmsGoodsEntity.setAtlas(null);
                            cmsGoodsPojo.setCmsGoodsEntity(cmsGoodsEntity);
                            // information
                            CmsGoodsInformationEntity cmsGoodsInformationEntity = new CmsGoodsInformationEntity();
                            cmsGoodsInformationEntity.setGoodid(incodes);
                            cmsGoodsInformationEntity.setEcnn(1);
                            cmsGoodsInformationEntity.setAtlas("");
                            cmsGoodsInformationEntity.setContent(null);
                            cmsGoodsInformationEntity.setActivity(0);
                            cmsGoodsInformationEntity.setEcnnnumber("");
                            cmsGoodsInformationEntity.setTariffs(0);
                            cmsGoodsInformationEntity.setTariffsrate(0);
                            cmsGoodsInformationEntity.setInspectionCharges(0);
                            cmsGoodsInformationEntity.setInspectionChargesFee(cmsGoodsEntity.getInspectionChargesFee());
                            cmsGoodsInformationEntity.setParams(null);
                            cmsGoodsInformationEntity.setCreatedAt(new Date());
                            cmsGoodsPojo.setCmsGoodsInformationEntity(cmsGoodsInformationEntity);
                            // price
                            List<CmsPricesEntity> pricesEntities = new ArrayList<>(6);
                            for (Map<String, String> m : ladderPrice) {
                                CmsPricesEntity pricesEntity = new CmsPricesEntity();
                                pricesEntity.setLadderid(0);
                                pricesEntity.setGoodid(incodes);
                                pricesEntity.setMin(Long.parseLong(m.get("min")));
                                pricesEntity.setMax(Long.parseLong(m.get("max")));
                                pricesEntity.setPrice(BigDecimal.valueOf(Double.parseDouble(m.get("price"))));
                                pricesEntity.setCurrency(Integer.parseInt(m.get("currency")));
                                pricesEntity.setPosition(Integer.parseInt(m.get("position")));
                                pricesEntity.setDiscountRate(new BigDecimal(m.get("discount_rate")));
                                pricesEntity.setDiscountPrice(new BigDecimal(m.get("discount_price")));
                                pricesEntity.setPublish(0);
                                pricesEntity.setCreatedAt(new Date());
                                pricesEntity.setUpdatedAt(new Date());
                                pricesEntities.add(pricesEntity);
                            }
                            cmsGoodsPojo.setCmsPricesEntityList(pricesEntities);
                            master.add(cmsGoodsPojo);
                        } catch (Exception e) {
                            log.warn("解析CoreStaffList数据异常，将丢弃此条数据");
                            retryOperateLogHelper.add(coreStaffStockExcelData, supplierId, e.toString());
                        }
                    }

                }, sheetName);
            }
        } finally {
            master.isBegin = false;
            cmsTopicUpdateSumLogService.insertBySum(sum.longValue(), pk);
        }
    }


}
